package com.apkplug.downloaddemo;
import java.io.File;
import java.util.List;
import org.apkplug.app.FrameworkFactory;
import org.apkplug.app.FrameworkInstance;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import com.apkplug.download.BundleActivator.DownLoadActivator;
import com.apkplug.download.service.FileDownload;
import com.apkplug.download.service.FileDownloadCallBack;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
	private FrameworkInstance frame=null;
	TextView info=null;
	StringBuffer sb=new StringBuffer();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		info=(TextView) this.findViewById(R.id.info);
		 try
	        {
	        	//启动框架
				//文档见 http://www.apkplug.com/javadoc/Maindoc1.4.6/
				//org.apkplug.app 
				//     接口 FrameworkInstance
				//com.apkplug.appServiceManager 为Service.jar包提供的插件托管服务启动BundleActivator
				List activators=new java.util.ArrayList<BundleActivator>();
	            //将服务加入框架，框架将在启动时启动这些服务
				activators.add(new DownLoadActivator());
				frame=FrameworkFactory.getInstance().start(activators,this,new MyProperty(this.getApplicationContext()));
				addMsg("apkplug框架启动成功");
				BundleContext context =frame.getSystemBundleContext();
				File f=new File(getFilesDir(),"download.html");
				downloadService(context,"http://www.apkplug.com",f.getAbsolutePath(),new FileDownloadCallBack(){
					@Override
					public void onDownLoadSuccess(String file) {
						System.out.println("下载成功:"+file);
						addMsg("下载成功:"+file);
					}

					@Override
					public void onFailure(int errorNo ,String strMsg) {
						Log.e("apkplug", "下载失败:"+strMsg);
						addMsg("下载失败:"+strMsg);
					}

					@Override
					public void onProgress(int bytesWritten, int totalSize,String Speed) {
						Log.d("apkplug", String.format("Progress %d from %d (%d%%)", bytesWritten, totalSize, (totalSize > 0) ? (int)(((float)bytesWritten / (float)totalSize) * 100) : -1));
						addMsg(String.format("Progress %d from %d (%d%%) speed %s", bytesWritten, totalSize, (totalSize > 0) ? (int)(((float)bytesWritten / (float)totalSize) * 100) : -1,Speed));
					}
			
				});
	        }
	        catch (Exception ex)
	        {
	            System.err.println("Could not create : " + ex);
	            addMsg("apkplug框架启动失败");
	            ex.printStackTrace();
	            int nPid = android.os.Process.myPid();
				android.os.Process.killProcess(nPid);
	        }
	}
	/**
	 * 添加打印消息
	 * @param msg
	 */
	public void addMsg(String msg){
		sb.append(msg+"\n");
		info.post(new Runnable(){
			@Override
			public void run() {
				info.setText(sb.toString());
			}	
		});
	}
	/**
	 * 文件下载服务
	 * OSGI服务为暂态(可能随插件的安装与卸载随时关闭或启动) 所以我们尽量在每次使用是查询一次
	 * @param mcontext
	 * @param downurl
	 * @param filepath
	 * @param CallBack
	 * @throws Exception
	 */
	public void downloadService(BundleContext mcontext,String downurl,String filepath,FileDownloadCallBack CallBack) throws Exception{
		ServiceReference reference=mcontext.getServiceReference(FileDownload.class.getName());
    	if(null!=reference){
    		FileDownload service=(FileDownload) mcontext.getService(reference);
    		if(service!=null){
    			addMsg("找到FileDownload服务并开始下载文件");
    			service.download(getBaseContext(), downurl,filepath, CallBack);
    		}else{
    			addMsg("FileDownload不可用");
    		}
    		mcontext.ungetService(reference);
    	}else{
    		addMsg("没有找到FileDownload服务");
    	}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
